# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:ios)

platform :ios do
  lane :add_build do
    increment_build_number(
      build_number: latest_testflight_build_number + 1,
      xcodeproj: "ZenFlipClock2.xcodeproj"
    )
  end

  desc "Release new version to App Store"
  lane :release do
    app_store_connect_api_key(
      key_id: "46J9J6785P",
      issuer_id: "69a6de89-1346-47e3-e053-5b8c7c11a4d1",
      key_filepath: "./AuthKey_46J9J6785P.p8",
      duration: 1200,
      in_house: false
    )
    
    # Read localized release notes with existence check
    changelog_en = File.read("changelog/en.txt") if File.exist?("changelog/en.txt")
    changelog_zh = File.read("changelog/zh-Hans.txt") if File.exist?("changelog/zh-Hans.txt")
    changelog_zh_hant = File.read("changelog/zh-Hant.txt") if File.exist?("changelog/zh-Hant.txt")
    changelog_ja = File.read("changelog/ja.txt") if File.exist?("changelog/ja.txt")
    changelog_ko = File.read("changelog/ko.txt") if File.exist?("changelog/ko.txt")
    changelog_de = File.read("changelog/de.txt") if File.exist?("changelog/de.txt")
    changelog_fr = File.read("changelog/fr.txt") if File.exist?("changelog/fr.txt")
    changelog_pt = File.read("changelog/pt-BR.txt") if File.exist?("changelog/pt-BR.txt")
    changelog_th = File.read("changelog/th.txt") if File.exist?("changelog/th.txt")
    changelog_vi = File.read("changelog/vi.txt") if File.exist?("changelog/vi.txt")
    changelog_es = File.read("changelog/es.txt") if File.exist?("changelog/es.txt")
    # Read keywords from fastlane/keywords/ (explicitly)
    # 从 fastlane/keywords/ 明确读取关键词
    keywords_folder_path = "keywords/" # 相对于 fastlane 文件夹
    app_keywords = {}

    # 区域设置映射表，确保与 App Store Connect 兼容
    locale_map = {
      'en' => 'en-US',
      'zh-Hans' => 'zh-Hans',
      'zh-Hant' => 'zh-Hant',
      'ja' => 'ja',
      'ko' => 'ko',
      'de' => 'de-DE',
      'fr' => 'fr-FR',
      'es' => 'es-ES',
      'pt-BR' => 'pt-BR',
      'th' => 'th',
      'vi' => 'vi'
    }

    # Read English keywords
    en_keyword_path = File.join(keywords_folder_path, "en.txt")
    if File.exist?(en_keyword_path)
      keywords_string = File.read(en_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['en']] = keywords_string unless keywords_string.empty?
    end

    # Read Simplified Chinese keywords
    zh_hans_keyword_path = File.join(keywords_folder_path, "zh-Hans.txt")
    if File.exist?(zh_hans_keyword_path)
      keywords_string = File.read(zh_hans_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['zh-Hans']] = keywords_string unless keywords_string.empty?
    end
    
    # Read Traditional Chinese keywords
    zh_hant_keyword_path = File.join(keywords_folder_path, "zh-Hant.txt")
    if File.exist?(zh_hant_keyword_path)
      keywords_string = File.read(zh_hant_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['zh-Hant']] = keywords_string unless keywords_string.empty?
    end

    # Read Japanese keywords
    ja_keyword_path = File.join(keywords_folder_path, "ja.txt")
    if File.exist?(ja_keyword_path)
      keywords_string = File.read(ja_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['ja']] = keywords_string unless keywords_string.empty?
    end

    # Read Korean keywords
    ko_keyword_path = File.join(keywords_folder_path, "ko.txt")
    if File.exist?(ko_keyword_path)
      keywords_string = File.read(ko_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['ko']] = keywords_string unless keywords_string.empty?
    end

    # Read German keywords
    de_keyword_path = File.join(keywords_folder_path, "de.txt")
    if File.exist?(de_keyword_path)
      keywords_string = File.read(de_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['de']] = keywords_string unless keywords_string.empty?
    end

    # Read French keywords
    fr_keyword_path = File.join(keywords_folder_path, "fr.txt")
    if File.exist?(fr_keyword_path)
      keywords_string = File.read(fr_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['fr']] = keywords_string unless keywords_string.empty?
    end

    # Read Spanish keywords
    es_keyword_path = File.join(keywords_folder_path, "es.txt")
    if File.exist?(es_keyword_path)
      keywords_string = File.read(es_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['es']] = keywords_string unless keywords_string.empty?
    end
    
    # Read Brazilian Portuguese keywords
    pt_br_keyword_path = File.join(keywords_folder_path, "pt-BR.txt")
    if File.exist?(pt_br_keyword_path)
      keywords_string = File.read(pt_br_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['pt-BR']] = keywords_string unless keywords_string.empty?
    end

    # Read Thai keywords
    th_keyword_path = File.join(keywords_folder_path, "th.txt")
    if File.exist?(th_keyword_path)
      keywords_string = File.read(th_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['th']] = keywords_string unless keywords_string.empty?
    end

    # Read Vietnamese keywords
    vi_keyword_path = File.join(keywords_folder_path, "vi.txt")
    if File.exist?(vi_keyword_path)
      keywords_string = File.read(vi_keyword_path).strip.gsub(/\s*,\s*/, ',').gsub(/,$/, '')
      app_keywords[locale_map['vi']] = keywords_string unless keywords_string.empty?
    end

    # 如果存在 en-US (英语) 关键词且不为空，则将其用作默认关键词
    if app_keywords.key?(locale_map['en']) && !app_keywords[locale_map['en']].empty?
      app_keywords['default'] = app_keywords[locale_map['en']]
    end
    
    if app_keywords.empty? || app_keywords.values.all?(&:empty?)
      UI.important("No keywords found in '#{keywords_folder_path}' or all keyword files are empty. Keywords will not be updated for this release.")
    else
      UI.message("Keywords to be uploaded: #{app_keywords.inspect}") 
    end
    
    git_add
    increment_build_number(
      build_number: latest_testflight_build_number + 1,
      xcodeproj: "ZenFlipClock2.xcodeproj"
    )
    
    version = get_version_number(xcodeproj: "ZenFlipClock2.xcodeproj", target: "ZenFlipClock2 (iOS)")
    build_number = get_build_number(xcodeproj: "ZenFlipClock2.xcodeproj")

    tag_version = "#{version}/#{build_number}"
    if not git_tag_exists(tag: tag_version)
      add_git_tag(
        tag: tag_version
      )
      # Cascade 注释：仅在存在文件变更时才执行版本提交，避免空提交导致 lane 失败
      changed_files = sh("git diff --name-only HEAD").strip
      if changed_files.empty?
        UI.important("No file changes detected after build bump. Skip commit_version_bump.")
      else
        commit_version_bump
      end
    end

    sync_code_signing(type: "appstore")
    match(type: "appstore", app_identifier: ["com.mad.FlipClock", "com.mad.FlipClock.ZFCWidget"])
    build_app(scheme:"ZenFlipClock2")
    
    # Upload to App Store with release notes
    deliver(
      keywords: app_keywords,
      submit_for_review: true,
      automatic_release: true,
      force: true,
      skip_metadata: false,
      skip_screenshots: true,
      skip_binary_upload: false,
      precheck_include_in_app_purchases: false,
      run_precheck_before_submit: false,
      submission_information: {
        add_id_info_uses_idfa: false,
        export_compliance_uses_encryption: false,
        export_compliance_platform: 'ios'
      },
      release_notes: {
        'default' => changelog_en,
        'en-US' => changelog_en,
        'zh-Hans' => changelog_zh,
        'zh-Hant' => changelog_zh_hant,
        'ja' => changelog_ja,
        'ko' => changelog_ko,
        'de-DE' => changelog_de,
        'fr-FR' => changelog_fr,
        'pt-BR' => changelog_pt,
        'th' => changelog_th,
        'vi' => changelog_vi,
        'es-ES' => changelog_es
      }
    )

    slack(
      message: "Version: #{version} (Build: #{build_number}) has been uploaded to App Store",
      slack_url: "https://hooks.slack.com/services/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"
    )
  end

  desc "Build and upload to TestFlight only"
  lane :beta do
    app_store_connect_api_key(
      key_id: "46J9J6785P",
      issuer_id: "69a6de89-1346-47e3-e053-5b8c7c11a4d1",
      key_filepath: "./AuthKey_46J9J6785P.p8",
      duration: 1200,
      in_house: false
    )

    # Cascade 注释：与 release 保持一致，先纳入当前变更再自增构建号
    git_add
    increment_build_number(
      build_number: latest_testflight_build_number + 1,
      xcodeproj: "ZenFlipClock2.xcodeproj"
    )

    version = get_version_number(xcodeproj: "ZenFlipClock2.xcodeproj", target: "ZenFlipClock2 (iOS)")
    build_number = get_build_number(xcodeproj: "ZenFlipClock2.xcodeproj")

    tag_version = "#{version}/#{build_number}"
    if not git_tag_exists(tag: tag_version)
      add_git_tag(
        tag: tag_version
      )
      # Cascade 注释：仅在存在文件变更时才执行版本提交，避免空提交导致 lane 失败
      changed_files = sh("git diff --name-only HEAD").strip
      if changed_files.empty?
        UI.important("No file changes detected after build bump. Skip commit_version_bump.")
      else
        commit_version_bump
      end
    end

    sync_code_signing(type: "appstore")
    match(type: "appstore", app_identifier: ["com.mad.FlipClock", "com.mad.FlipClock.ZFCWidget"])
    build_app(scheme: "ZenFlipClock2")

    # Cascade 注释：仅上传到 TestFlight，不提交 App Store 审核
    upload_to_testflight(
      skip_waiting_for_build_processing: true,
      distribute_external: false,
      changelog: File.read("changelog/en.txt")
    )

    slack(
      message: "Version: #{version} (Build: #{build_number}) has been uploaded to TestFlight",
      slack_url: "https://hooks.slack.com/services/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"
    )
  end
  
  lane :certificates do
    match(app_identifier: ["com.mad.FlipClock", "com.mad.FlipClock.ZFCWidget"])
  end
  
  lane :checkversion do
    version = get_version_number(xcodeproj: "ZenFlipClock2.xcodeproj", target: "ZenFlipClock2 (iOS)")
    build_number = get_build_number(xcodeproj: "ZenFlipClock2.xcodeproj")
    puts("Version: #{version} (Build: #{build_number})")
  end
  
  desc "Upload release notes to App Store"
  lane :upload_notes do
    app_store_connect_api_key(
      key_id: "46J9J6785P",
      issuer_id: "69a6de89-1346-47e3-e053-5b8c7c11a4d1",
      key_filepath: "./AuthKey_46J9J6785P.p8",
      duration: 1200,
      in_house: false
    )
    
    # Read localized release notes with existence check
    changelog_en = File.read("changelog/en.txt") if File.exist?("changelog/en.txt")
    changelog_zh = File.read("changelog/zh-Hans.txt") if File.exist?("changelog/zh-Hans.txt")
    changelog_zh_hant = File.read("changelog/zh-Hant.txt") if File.exist?("changelog/zh-Hant.txt")
    changelog_ja = File.read("changelog/ja.txt") if File.exist?("changelog/ja.txt")
    changelog_ko = File.read("changelog/ko.txt") if File.exist?("changelog/ko.txt")
    changelog_de = File.read("changelog/de.txt") if File.exist?("changelog/de.txt")
    changelog_fr = File.read("changelog/fr.txt") if File.exist?("changelog/fr.txt")
    changelog_pt = File.read("changelog/pt-BR.txt") if File.exist?("changelog/pt-BR.txt")
    changelog_th = File.read("changelog/th.txt") if File.exist?("changelog/th.txt")
    changelog_vi = File.read("changelog/vi.txt") if File.exist?("changelog/vi.txt")
    changelog_es = File.read("changelog/es.txt") if File.exist?("changelog/es.txt")

    version = get_version_number(xcodeproj: "ZenFlipClock2.xcodeproj", target: "ZenFlipClock2 (iOS)")
    
    # Debug output
    puts "Current version: #{version}"
    
    # Upload release notes only
    deliver(
      app_version: version,
      submit_for_review: false,
      automatic_release: true,
      force: true,
      skip_metadata: false,
      skip_screenshots: true,
      skip_binary_upload: true,
      precheck_include_in_app_purchases: false,
      run_precheck_before_submit: false,
      submission_information: {
        add_id_info_uses_idfa: false,
        export_compliance_uses_encryption: false,
        export_compliance_platform: 'ios'
      },
      release_notes: {
        'default' => changelog_en,
        'en-US' => changelog_en,
        'zh-Hans' => changelog_zh,
        'zh-Hant' => changelog_zh_hant,
        'ja' => changelog_ja,
        'ko' => changelog_ko,
        'de-DE' => changelog_de,
        'fr-FR' => changelog_fr,
        'pt-BR' => changelog_pt,
        'th' => changelog_th,
        'vi' => changelog_vi,
        'es-ES' => changelog_es
      }
    )

    slack(
      message: "Release notes for version #{version} have been uploaded to App Store",
      slack_url: "https://hooks.slack.com/services/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"
    )
  end
end
